package com.techsoul.common.security.aspect;

import com.techsoul.common.core.pojo.param.BaseSearchParam;
import com.techsoul.common.core.pojo.vo.OrgVo;
import com.techsoul.common.core.pojo.vo.RoleVo;
import com.techsoul.common.core.util.ServletUtils;
import com.techsoul.common.core.util.collection.ListUtils;
import com.techsoul.common.core.util.lang.StringUtils;
import com.techsoul.common.core.util.spring.SpringUtils;
import com.techsoul.common.security.annotation.DataScope;
import com.techsoul.common.security.enums.DataScopeEnum;
import com.techsoul.common.security.exception.DataScopeException;
import com.techsoul.common.security.pojo.LoginUser;
import com.techsoul.common.security.service.TokenService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.stream.Collectors;

/**
 * 数据过滤处理
 *
 * @author liuen
 */
@Aspect
@Component
public class DataScopeAspect {

    // 配置织入点
    @Pointcut("@annotation(com.techsoul.common.security.annotation.DataScope)")
    public void dataScopePointCut() {
    }

    @Before("dataScopePointCut()")
    public void doBefore(JoinPoint point) throws Throwable {
        handleDataScope(point);
    }

    protected void handleDataScope(final JoinPoint joinPoint) {
        // 获得注解
        DataScope controllerDataScope = getAnnotationLog(joinPoint);
        if (controllerDataScope == null) {
            return;
        }
        // 获取当前的用户
        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        if (StringUtils.isNotNull(loginUser)) {
            // 如果是超级管理员，则不过滤数据
            if (StringUtils.isNotNull(loginUser.getUser()) && !loginUser.getUser().isAdmin()) {
                dataScopeFilter(joinPoint, loginUser, controllerDataScope.orgAlias(), controllerDataScope.userAlias());
            }
        }
    }

    /**
     * 数据范围过滤
     *
     * @param joinPoint 切点
     * @param loginUser 登录用户
     * @param userAlias 别名
     */
    public static void dataScopeFilter(JoinPoint joinPoint, LoginUser loginUser, String orgAlias, String userAlias) {
        StringBuilder sb = new StringBuilder();
        boolean isDataScopeAll = false; // 是否有全部数据权限
        for (RoleVo role : loginUser.getRoles()) {
            String dataScopeType = role.getDataScopeType();
            if (DataScopeEnum.ALL.getValue().equals(dataScopeType)) {
                isDataScopeAll = true;
                // 清空数据权限限制
                sb = new StringBuilder();
                break;
            }
            if (DataScopeEnum.ORG.getValue().equals(dataScopeType)) {
                if (StringUtils.isNotBlank(orgAlias)) {
                    sb.append(StringUtils.format(" OR {}.id IN ( SELECT id FROM sys_org WHERE id = {} or find_in_set( {} , ancestors ) )", orgAlias, loginUser.getUser().getOrgId(), loginUser.getUser().getOrgId()));
                }
            }
            if (DataScopeEnum.SELF.getValue().equals(dataScopeType)) {
                if (StringUtils.isNotBlank(userAlias)) {
                    sb.append(StringUtils.format(" OR {}.id = {} ", userAlias, loginUser.getUser().getId()));
                }
            }
            if (DataScopeEnum.CUSTOM.getValue().equals(dataScopeType)) {
                if (StringUtils.isNotBlank(orgAlias) && ListUtils.isNotEmpty(role.getRoleOrgs())) {
                    String orgIds = role.getRoleOrgs().stream().map(OrgVo::getId).distinct().collect(Collectors.joining(","));
                    sb.append(StringUtils.format(" OR {}.id IN ({}) ", orgAlias, orgIds));
                }
            }
        }

        if (StringUtils.isNotBlank(sb.toString())) {
            Object params = joinPoint.getArgs()[0];
            if (StringUtils.isNotNull(params) && params instanceof BaseSearchParam) {
                BaseSearchParam baseSearchParam = (BaseSearchParam) params;
                baseSearchParam.setDataScope(" AND (" + sb.substring(4) + ")");
            }
        } else if (!isDataScopeAll){
            throw new DataScopeException();
        }
    }

    /**
     * 是否存在注解，如果存在就获取
     */
    private DataScope getAnnotationLog(JoinPoint joinPoint) {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();

        if (method != null) {
            return method.getAnnotation(DataScope.class);
        }
        return null;
    }

}
